package com.romejiang;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.romejiang.events.ReceiveMessageEvent;
import com.romejiang.models.MiningInfo;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.yeauty.annotation.*;
import org.yeauty.pojo.ParameterMap;
import org.yeauty.pojo.Session;

import java.io.IOException;

@ServerEndpoint(port = 8088, path = "/mining", host = "localhost")
@Component
public class MiningWebSocket {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ApplicationEventPublisher publisher;


    @OnOpen
    public void onOpen(Session session, HttpHeaders headers, ParameterMap parameterMap) throws IOException {
        System.out.println("new connection");

//        String paramValue = parameterMap.getParameter("paramKey");
//        System.out.println(paramValue);
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        System.out.println("one connection closed");
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        System.out.println(message);
        try {
            MiningInfo bean = objectMapper.readValue(message, MiningInfo.class);
            publisher.publishEvent(new ReceiveMessageEvent(session, bean));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnBinary
    public void onBinary(Session session, byte[] bytes) {
        for (byte b : bytes) {
            System.out.println(b);
        }
        session.sendBinary(bytes);
    }

    @OnEvent
    public void onEvent(Session session, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    System.out.println("read idle");
                    break;
                case WRITER_IDLE:
                    System.out.println("write idle");
                    break;
                case ALL_IDLE:
                    System.out.println("all idle");
                    break;
                default:
                    break;
            }
        }
    }


    @EventListener
    public void handleMessage(ReceiveMessageEvent event) {
        System.out.println(event.getMessage() + " in handleMessage...");

        event.getSession().sendText("server");


    }

}